import createDOMString from '../../utils/createDOMString';
import createElement from '../../utils/createElement';
import getColor from '../../utils/getColor';

const getPosition = props => {
  switch (props.type) {
    case 'part':
      return 'absolute';
    case 'fullscreen':
      return 'fixed';
    default:
      return 'fixed';
  }
};

createElement({
  name: 'cms-loading',
  props: {
    loading: cur => {
      return typeof cur === 'string' && cur !== 'false';
    },
    type: cur => {
      const typeArr = ['part', 'fullscreen'];
      return typeArr.includes(cur) ? cur : 'fullscreen';
    },
  },
  defaultProps: {
    loading: false,
    type: 'fullscreen',
  },
  render(props) {
    return createDOMString(props)`
      <style>
        :host {
          --scale: 0.85;
          --edge: 50px;
        }
        :host {
          position: ${getPosition};
          left: 0px;
          top: 0px;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.1);
          display: ${props => (props.loading ? 'flex' : 'none')};
          flex-direction: column;
          justify-content: center;
          align-items: center;
          font-size: 24px;
          z-index: 100;
        }
        :host > .load {
          position: relative;
          width: var(--edge, 50px);
          height: var(--edge, 50px);
          transform-origin: center center;
          animation: rotate 2s linear infinite;
        }
        :host > .load > .load-item {
          --radius: calc((5 + var(--i, 1)) * 1px);
          position: absolute;
          transform-origin: calc(var(--edge, 50px) / 2) calc(var(--edge, 50px) / 2);
          transform: rotateZ(calc(360 / 9 * var(--i) * 1deg));
          width: var(--radius);
          height: var(--radius);
          border-radius: 50%;
          background-color: ${getColor('primary')};
        }
        ::slotted(*) {
          margin-top: 20px;
        }
        @keyframes rotate {
          from {
            transform: rotate(0deg) scale(var(--scale, 1));
          }
          to {
            transform: rotate(360deg) scale(var(--scale, 1));
          }
        }
      </style>
      <div class="load">
        ${
          () =>
            new Array(8) // 创建长度为8的数组，全部填充为undefined
              .fill(0) // 为什么要fill(0), 因为map函数会跳过值为undefined的内容
              .map((_, i) => `<div class="load-item" style="--i: ${i + 1}"></div>`) //创建8个圆球，达成loading图标的效果
              .join('') // 连接符使用空字符串，不传时默认为逗号
        }
      </div>
      <slot></slot>
      <slot name="footer"></slot>
    `;
  },
});
